from django import forms

from App.bootstrap import BootStrapForm
from App.global_var import get_global_code
from App.models import User


# 登录表单，继承BootStrapForm类
class LoginForm(BootStrapForm):
    username = forms.CharField(
        min_length=3,
        max_length=20,
        label='用户名',
        widget=forms.TextInput(attrs={
            # 对于所有的插件而言，后端开发者均不需要关心样式而只需要关心功能和检查
            'placeholder': '请输入用户名',
        }),
    )
    password = forms.CharField(
        min_length=8,
        label='密码',
        widget=forms.PasswordInput(attrs={
            'placeholder': '请输入密码'
        }),
    )
    code = forms.CharField(
        max_length=5,
        label='验证码',
        widget=forms.TextInput(attrs={
            'placeholder': '请输入验证码'
        })
    )

    class Meta:
        model = User  # 必须为数据库中的某个class
        fields = "__all__"  # 获取数据库中所有字段

    # 对用户名进行错误判定
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if username == '':
            raise forms.ValidationError('用户名不可为空')

        # 判断用户是否存在，若存在则进行验证
        if not User.objects.filter(username=username):
            raise forms.ValidationError('用户名不存在')
        return username

    # 对密码进行错误判定
    def clean_password(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        if username == '' or password == '':
            raise forms.ValidationError('密码不可为空')

        # 判断用户是否存在，若存在则进行验证
        if User.objects.filter(username=username):
            if not User.objects.filter(username=username)[0].password == password:
                raise forms.ValidationError('密码错误')
            else:
                return username, password
        else:
            raise forms.ValidationError('')

    # 目前字段少不需要这个函数，请保留
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)

    # 对验证码进行验证
    def clean_code(self):
        # 全局变量
        text_code = get_global_code()
        # 获取用户输入的验证码
        input_code = self.cleaned_data.get('code')
        if not input_code.upper() == text_code.upper():
            raise forms.ValidationError('验证码输入错误')
        return input_code
